<template>
  <div class="content">
    <el-button v-if="this.import" icon="el-icon-document" @click.stop="importData"> 导入 </el-button>
    <el-button v-if="this.export" icon="el-icon-document" @click.stop="exportData"> 导出</el-button>
    <el-button icon="el-icon-setting" @click.stop="pageSetting"> 设置</el-button>
    <el-button v-if="this.export" icon="el-icon-setting" @click.stop="exportSetting"> 导出设置</el-button>
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import UploadExcel from '@/components/UploadExcel/UploadExcel'
import PageSetting from '@/components/PageSetting/index'
import ExportSetting from '@/components/ExportSetting/index'
import { initPageSetting } from '@/utils/table' // 表格通用方法
export default {
  name: 'ImportExportSetting',
  props: {
    export: { // 是否需要导出
      type: Boolean,
      default() {
        return true
      }
    },
    import: {// 是否需要导入
      type: Boolean,
      default() {
        return true
      }
    },
    page: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  methods: {
    // 刷新
    refresh() {
      this.page.refresh()
    },
    // 导出数据
    exportData() {
      // 处理表头字段
      const tHeader = []
      let exportColumns = this.page.exportObject.exportColumns
      // 如果有额外的导出字段
      if (this.page.exportObject.extraExportColumns && this.page.exportObject.extraExportColumns !== []) {
        exportColumns = exportColumns.concat(this.page.exportObject.extraExportColumns)
      }

      exportColumns.forEach(item => {
        if (typeof item.export === 'undefined' || item.export) { tHeader.push(item.label) }
      })

      if (!this.page.exportObject.getData && this.page.selectionsAll.length) { // 有勾选
        // 处理表体数据
        const data = this.handleExportData(this.page.selectionsAll)
          import('@/vendor/Export2Excel').then(excel => {
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.page.pageId + ' ' + parseTime(new Date(), '{y}-{m}-{d}'),
              bookType: this.page.exportObject.exportType
            })
          })
      } else {
        // 获取导出数据（未勾选时导出所有行）
        this.page.getExportData(this.page.selectionsAll).then(res => {
          const data = this.handleExportData(res.data)
          // 处理表体数据
            import('@/vendor/Export2Excel').then(excel => {
              excel.export_json_to_excel({
                header: tHeader,
                data,
                filename: this.page.pageId + ' ' + parseTime(new Date(), '{y}-{m}-{d}'),
                bookType: this.page.exportObject.exportType
              })
            })
        })
      }
    },
    // 导入按钮
    importData() {
      this.$layer.iframe({
        content: {
          content: UploadExcel,
          parent: this,
          data: {
            type: this.page.importObject.type,
            headers: this.page.importObject.headers
          }
        },
        area: ['800px', '500px'],
        title: '导入数据',
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 保存导入数据
    saveImportData(data) {
      return this.page.saveImportData({ data: JSON.stringify(data) })
    },
    // 页面设置按钮
    pageSetting() {
      this.$layer.iframe({
        content: {
          content: PageSetting,
          parent: this,
          data: {
            pageId: this.page.pageId,
            sort: this.page.pageData,
            columns: this.page.tableColumns
          }
        },
        area: ['1200px', '600px'],
        title: '页面设置',
        resize: false,
        shade: true,
        shadeClose: true
      })
    },
    // 初始化页面设置
    initPageSetting() {
      initPageSetting(this.page)
    },
    // 导出设置按钮
    exportSetting() {
      this.$layer.iframe({
        content: {
          content: ExportSetting,
          parent: this,
          data: {
            prefix: this.page.pageId,
            exportObject: this.page.exportObject
          }
        },
        area: ['800px', '600px'],
        title: '导出设置',
        resize: false,
        shade: true,
        shadeClose: true
      })
    },
    // 处理导出数据
    handleExportData(data) {
      // 如果原页面有处理方法，则优先调用原页面的方法（提供可自定义的可能，例如性别：1:男，2:女）
      // if (typeof this.page.handleExportData === 'function') {
      //   this.page.handleExportData(data).then(res => {
      //     return res
      //   })
      // } else {
      // 原页面没有处理方法的话，使用默认的处理方法
      // 需要导出的字段（包含export=false的字段）
      let exportColumns = this.page.exportObject.exportColumns
      // 如果有额外的导出字段
      if (this.page.exportObject.extraExportColumns && this.page.exportObject.extraExportColumns !== []) {
        exportColumns = exportColumns.concat(this.page.exportObject.extraExportColumns)
      }
      // 需要导出的字段（不包含export=false的字段）
      const columns = []
      // 需要导出的数据
      const exportData = []
      // 排除export=false的字段
      exportColumns.forEach(item => {
        if (typeof item.export === 'undefined' || item.export) { columns.push(item.prop) }
      })
      data.forEach(item => {
        // 一行数据
        const cacheData = []
        columns.forEach(item2 => {
          // 把这行数据的item2属性放入导出的数据的行
          if (item[item2] === undefined) { cacheData.push('') } else {
            cacheData.push(item[item2])
          }
        })
        exportData.push(cacheData)
      })
      return exportData
    }
    // }
  }
}
</script>

<style scoped>
.content{
  display: inline-block;
}
</style>
